package com.acme.bankapp.domain.bank;

import com.acme.bankapp.domain.bank.notifications.ClientNotificationEmail;
import com.acme.bankapp.domain.bank.notifications.ClientRegistrationListener;
import com.acme.bankapp.exceptions.BankException;
import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.exceptions.ClientsOverflowException;
import com.acme.bankapp.service.bank.BankService;
import com.acme.bankapp.service.bank.Configuration;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Student on 14.11.2014.
 */
public class Bank implements Serializable {
    private Set<Client> clients;
    private ClientRegistrationListener[] listeners;

    public Bank() {
        clients = new HashSet<>();

        listeners = new ClientRegistrationListener[] { new ClientRegistrationListener() {
            @Override
            public void onClientAdded(Client c) {
                System.out.println(c.getName());
            }

            @Override
            public void stopListener() {

            }
        },  new ClientNotificationEmail()
        };

    }

    public void addClient(Client newClient) throws BankException {
        int counter = clients.size();

        if(counter == Configuration.getClientsNumber()) {
            throw new ClientsOverflowException("maximum clients number is " + Configuration.getClientsNumber());
        }

        for (Client client:clients) {
            if (newClient.getName().equals(client.getName())) {
                throw new ClientExistsException(newClient);
            }
        }

        clients.add(newClient);

        for (ClientRegistrationListener listener: listeners) {
            listener.onClientAdded(newClient);
        }
        BankService.saveBank(this, Configuration.getSerPath());
    }

    public ClientRegistrationListener[] getListeners() {
        return listeners;
    }

    public ArrayList<Client> getClients() {
        return new ArrayList<Client>(clients);
    }

    public void stopListeners() {
        for (ClientRegistrationListener crl: listeners) {
            if (crl != null)
                crl.stopListener();
        }
    }
}
